# coding=utf-8
"""
Created on 2018年09月03日
"""

import requests
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
import json
from util_base.exception import UFOServiceException
from common_base.errors import AliveError
from common_base.constants import AliveConstant
import time
import uuid
import hashlib
from setting_base.setting import C


class AliveService(object):
    """
    调用其他模块
    """

    def __init__(self, url, processor=None):
        """
        Constructor
        """

        self._processor = processor
        self.url = url

#     @exception_transfer(UFOServiceException) 
    def call_api(self, cmdid, appid, params, userid='', is_async=False, files=None, callback=None, common=None, complete_response = False):
        """
        调用接口
        files: {
                "a": ('tests.png', open('../logs/tests.png', 'rb'))
                }
        """
        headers = dict()
        headers["cmdId"] = str(cmdid)
        headers["Timestamp"] = str(int(time.time() * 1000))
        headers["appId"] = appid
        headers["NonceStr"] = str(uuid.uuid1())[:32]
        headers["SignType"] = "MD5"

        if userid:
            body = {
                'common': {
                     'userId': userid,
                },
                'params': params
            }
        else:
            body = {
                'common': {
                    'userid': self._processor.userid
                },
                'params': params
            }
            
        if common:
            body['common'] = common
            
        secretKey = C("DAPP_INFO").get("internal_key", "")
        sign_str = '''AppID=%s&Body=%s&SignType=%s&Timestamp=%s&secretKey=%s'''\
                   %(appid, json.dumps(body), headers["SignType"], headers['Timestamp'], secretKey)
        headers['RequestSign'] = hashlib.md5(sign_str.encode()).hexdigest().upper()
        
        if is_async:
            assert not files, u'async mode not supported in internal multipart calls'
           
            # 异步调用
            client = AsyncHTTPClient()
            request = HTTPRequest(self.url, 'POST', headers, body=json.dumps(body))
            client.fetch(request, callback=callback if callback else None)
        else:
            if not files:
                res = requests.post(self.url, json=body, headers=headers, timeout=AliveConstant.TIMEOUT)
            else:
                body.update(body.pop('params'))
                res = requests.post(self.url, params=body, files=files, headers=headers, timeout=AliveConstant.TIMEOUT)
            if res.status_code != 200:
                raise UFOServiceException('URL:%s cmdid:%s ResCode:%s'% (self.url, headers['cmdId'], res.status_code))
            try:
                res_json = json.loads(res.text)
                
                if not complete_response:
                    assert res_json['common']['code'] == AliveError.SUCCESS
                    return res_json['data']
                else:
                    return res_json
            except:
                return dict()
#                 raise UFOServiceException(res.text.decode('unicode_escape'))
